# ==============================
# _*_ coding:utf-8 _*_
# _*_ by:zizle     _*_
# _*_ at:20230417  _*_
# ==============================
import time
from jose import jwt, JWTError
from fastapi import Header

from errors import LoginExpireError
from settings import APP_SECRET_KEY, TOKEN_EXPIRES


class Token:
    def __init__(self, payload: dict = None, expires: int = TOKEN_EXPIRES):
        self.payload = payload if payload else {}
        self.expires = expires

    def encode_token(self):
        self.payload.update({'exp': int(time.time() + self.expires)})
        return jwt.encode(self.payload, APP_SECRET_KEY, algorithm='HS256')

    @classmethod
    def decode_token(cls, token):
        try:
            payload = jwt.decode(token, APP_SECRET_KEY, algorithms='HS256')
        except JWTError:
            return None
        return payload


# token负载
class TokenPayload:
    def __init__(self, authorization: str = Header(...)):
        # print('authorization', authorization)
        self.uid = 0
        self.utp = 0
        payload = Token.decode_token(authorization)
        if not payload:
            raise LoginExpireError('登录已过期!')
        self.uid = payload['uid']
        self.utp = payload['utp']

    def user_id(self):
        return self.uid

    def user_type(self):
        return self.utp

    def __repr__(self):
        return 'TokenPayload(uid={},utp={})'.format(self.uid, self.utp)


class QuietTokenPayload:
    def __init__(self, authorization: str = Header(...)):
        self.uid = 0
        self.utp = 0
        payload = Token.decode_token(authorization)
        if payload:
            self.uid = payload['uid']
            self.utp = payload['utp']

    def user_id(self):
        return self.uid

    def user_type(self):
        return self.utp

